package io.xccit.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.xccit.common.exception.AuthCustomException;
import io.xccit.common.result.AjaxResult;
import io.xccit.common.utils.MD5;
import io.xccit.log.annotation.Log;
import io.xccit.log.enums.BusinessType;
import io.xccit.model.system.SysRole;
import io.xccit.model.system.SysUser;
import io.xccit.model.system.SysUserRole;
import io.xccit.model.vo.SysUserQueryVo;
import io.xccit.system.service.ISysRoleService;
import io.xccit.system.service.ISysUserRoleService;
import io.xccit.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author CH_ywx
 * @date 2023-06-22
 * @description
 */
@Api(tags = "用户接口")
@RestController
@CrossOrigin
@RequestMapping("/api/system/sysUser")
public class SysUserController {

    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysRoleService sysRoleService;
    @Resource
    private ISysUserRoleService sysUserRoleService;


    @Log(title = "获取用户列表")
    @PreAuthorize("hasAuthority('btn.sysUser.list')")
    @ApiOperation("用户列表")
    @GetMapping("/list")
    public AjaxResult<List<SysUser>> selectList(){
        return AjaxResult.ok(sysUserService.selectList());
    }

    @Log(title = "用户分页条件查询")
    @PreAuthorize("hasAuthority('btn.sysUser.list')")
    @ApiOperation("分页条件查询")
    @GetMapping("/page/{pageNo}/{pageSize}")
    public AjaxResult<IPage<SysUser>> selectPage(@ApiParam(value = "当前页",required = true) @PathVariable Long pageNo,
                                                 @ApiParam(value = "每页条数",required = true) @PathVariable Long pageSize,
                                                 @ApiParam("查询条件") SysUserQueryVo sysUserQueryVo){
        Page<SysUser> sysUserPage = new Page<>(pageNo, pageSize);
        IPage<SysUser> pageModel = sysUserService.selectPage(sysUserPage,sysUserQueryVo);
        return AjaxResult.ok(pageModel);
    }

    @Log(title = "根绝ID查询用户")
    @PreAuthorize("hasAuthority('btn.sysUser.list')")
    @ApiOperation("根据ID查询")
    @GetMapping("/get/{id}")
    public AjaxResult<SysUser> selectByID(@PathVariable Long id){
        SysUser sysUser = sysUserService.getById(id);
        return AjaxResult.ok(sysUser);
    }

    @Log(title = "添加用户",businessType = BusinessType.INSERT)
    @PreAuthorize("hasAuthority('btn.sysUser.add')")
    @ApiOperation("添加用户")
    @PostMapping("/save")
    public AjaxResult<String> saveUser(@RequestBody SysUser sysUser){
        //保证用户名不重复
        String username = sysUser.getUsername();
        boolean exist = sysUserService.userNameIsExist(username);
        if (exist){
            throw new AuthCustomException(2001,"用户名已存在");
        }
        String password = sysUser.getPassword();
        String encrypt = MD5.encrypt(password);
        sysUser.setPassword(encrypt);
        boolean save = sysUserService.save(sysUser);
        if (save){
            return AjaxResult.ok("添加成功");
        }else{
            return AjaxResult.fail("添加失败");
        }
    }

    @Log(title = "更新用户",businessType = BusinessType.UPDATE)
    @PreAuthorize("hasAuthority('btn.sysUser.update')")
    @ApiOperation("更新用户")
    @PutMapping("/update")
    public AjaxResult<String> updateUser(@ApiParam("用户信息") @RequestBody SysUser sysUser){
        boolean updated = sysUserService.updateById(sysUser);
        if (updated){
            return AjaxResult.ok("更新成功");
        }else{
            return AjaxResult.fail("更新失败");
        }
    }

    @Log(title = "删除用户",businessType = BusinessType.DELETE)
    @PreAuthorize("hasAuthority('btn.sysUser.remove')")
    @ApiOperation("删除用户")
    @DeleteMapping("/remove/{id}")
    public AjaxResult<String> deleteUserByID(@ApiParam(value = "用户ID",required = true) @PathVariable Long id){
        boolean removed = sysUserService.removeById(id);
        if (removed){
            return AjaxResult.ok("删除成功");
        }else{
            return AjaxResult.fail("删除失败");
        }
    }

    @Log(title = "批量删除用户",businessType = BusinessType.DELETE)
    @PreAuthorize("hasAuthority('btn.sysUser.remove')")

    @ApiOperation("批量删除")
    @DeleteMapping("/batchRemove")
    public AjaxResult<String> deleteBatch(@RequestBody List<Long> ids){
        boolean removed = sysUserService.removeByIds(ids);
        if (removed){
            return AjaxResult.ok("删除成功");
        }else{
            return AjaxResult.fail("删除失败");
        }
    }

    @Log(title = "根据用用户ID获取已拥有角色及角色列表")
    @PreAuthorize("hasAuthority('btn.sysRole.list')")
    @ApiOperation("根据用用户ID获取已拥有角色及角色列表")
    @GetMapping("/toAssign/{userID}")
    public AjaxResult<Map<String,Object>> toAssign(@PathVariable Long userID){
        System.out.println(userID);
        Map<String,Object> result = new HashMap<>();
        List<SysRole> allRoles = sysRoleService.selectList();
        List<SysRole> hadRoles = sysUserRoleService.getRoleByUserID(userID);
        result.put("allRoles",allRoles);
        result.put("hadRoles",hadRoles);
        System.out.println(hadRoles);
        return AjaxResult.ok(result);
    }

    @Log(title = "设置角色")
    @PreAuthorize("hasAuthority('btn.sysUser.assignRole')")
    @ApiOperation("设置角色")
    @PostMapping("/doAssign/{userID}")
    public AjaxResult<String> doAssign(@PathVariable Long userID,
                                       @RequestBody List<Long> roleIDs){
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId,userID);
        sysUserRoleService.remove(wrapper);
        SysUserRole sysUserRole = new SysUserRole();
        for (Long roleID : roleIDs) {
            sysUserRole.setUserId(userID);
            sysUserRole.setRoleId(roleID);
            sysUserRoleService.save(sysUserRole);
        }
        return AjaxResult.ok("设置成功");
    }
}
